package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bt.rpc.model.RpcResult;
import com.shop.admin.service.IPaperAssignService;
import com.shop.admin.validate.commons.PageValidate;
import com.shop.admin.validate.paper.PaperAssignCreateValidate;
import com.shop.admin.validate.paper.PaperAssignSearchValidate;
import com.shop.admin.vo.paper.PaperAssignDetailVo;
import com.shop.admin.vo.paper.PaperAssignListedVo;
import com.shop.common.core.PageResult;
import com.shop.common.entity.paper.Paper;
import com.shop.common.entity.paper.PaperAssign;
import com.shop.common.enums.UserTypeEnum;
import com.shop.common.mapper.paper.PaperAssignMapper;
import com.shop.common.mapper.paper.PaperMapper;
import com.shop.common.util.TimeUtils;
import com.wy.tech.model.SendExam;
import com.wy.tech.model.TechBasic;
import com.wy.tech.rpc.CollegeRpc;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 考试任务指派实现类
 * @author DragonDean
 */
@Service
public class PaperAssignServiceImpl implements IPaperAssignService {
        
    @Resource
    PaperAssignMapper paperAssignMapper;

    @Resource
    PaperMapper paperMapper;

    @Resource
    CollegeRpc collegeRpc;

    /**
     * 考试任务指派列表
     *
     * @author DragonDean
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<PaperAssignListedVo>
     */
    @Override
    public PageResult<PaperAssignListedVo> list(PageValidate pageValidate, PaperAssignSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<PaperAssign> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");

        paperAssignMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "=:paperId@paper_id:str",
            "=:userType@user_type:str",
            "=:userId@user_id:int",
            "=:userMobile@user_mobile:str",
            "=:status:int",
            "=:times:int",
            "=:highest:int",
        });

        IPage<PaperAssign> iPage = paperAssignMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<PaperAssignListedVo> list = new LinkedList<>();
        for(PaperAssign item : iPage.getRecords()) {
            PaperAssignListedVo vo = new PaperAssignListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 考试任务指派详情
     *
     * @author DragonDean
     * @param id 主键参数
     * @return PaperAssign
     */
    @Override
    public PaperAssignDetailVo detail(Integer id) {
        PaperAssign model = paperAssignMapper.selectOne(
                new QueryWrapper<PaperAssign>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        PaperAssignDetailVo vo = new PaperAssignDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 考试任务指派新增
     *
     * @author DragonDean
     * @param createValidate 参数
     */
    @Override
    public void add(PaperAssignCreateValidate createValidate) {
        RpcResult<TechBasic> result = null;
        if(createValidate.getUserType() == UserTypeEnum.TECHNICIAN.getCode()){
            result = collegeRpc.findTech(createValidate.getUserMobile());
        }
        if(createValidate.getUserType() == UserTypeEnum.PARTNER.getCode()){
            result = collegeRpc.findPartner(createValidate.getUserMobile());
        }
        if(createValidate.getUserType() == UserTypeEnum.HAN_DI.getCode()){
            result = collegeRpc.findHandiTech(createValidate.getUserMobile());
        }
        TechBasic techBasic = result != null ? result.getData() : null;
        Assert.notNull(techBasic, "用户不存在");

        Paper paper = paperMapper.selectOne(
                new QueryWrapper<Paper>()
                    .eq("id", createValidate.getPaperId())
                    .eq("is_delete", 0)
                    .last("limit 1"));
        Assert.notNull(paper, "试卷不存在");

        // 查询是否已有考试中
        PaperAssign paperAssign = paperAssignMapper.selectOne(
                new QueryWrapper<PaperAssign>()
                    .eq("paper_id", createValidate.getPaperId())
                    .eq("user_id", techBasic.getId())
                    .ne("status", 2)
                    .eq("is_delete", 0)
                    .and(i -> i.eq("days", 0)
                            .or()
                            .ge("create_time + days*86400", System.currentTimeMillis() / 1000)
                    )
                    .last("limit 1"));
        Assert.isNull(paperAssign, "已有考试任务,请勿重复指派");

        PaperAssign model = new PaperAssign();
        model.setPaperId(createValidate.getPaperId());
        model.setUserType(createValidate.getUserType());
        model.setUserId(techBasic.getId());
        model.setUserMobile(createValidate.getUserMobile());
        model.setUserName(techBasic.getName());
        if(createValidate.getDays() != null){
            model.setDays(createValidate.getDays());
        }
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        paperAssignMapper.insert(model);

        // 接口参数目前是userId, title, code,根据原型应该还需要时间（多久完成，否则下线）
        SendExam sendExam = new SendExam();
        sendExam.setUserId(techBasic.getId());
        sendExam.setTitle(paper.getTitle());
        sendExam.setCode(paper.getCode());
        Boolean sendResult = false;
        if(createValidate.getUserType() == UserTypeEnum.TECHNICIAN.getCode() || createValidate.getUserType() == UserTypeEnum.HAN_DI.getCode()){
            sendResult = collegeRpc.sendTechExam(sendExam).getData();
        }
        if(createValidate.getUserType() == UserTypeEnum.PARTNER.getCode()){
            sendResult = collegeRpc.sendPartnerExam(sendExam).getData();
        }
        Assert.isTrue(sendResult, "数据入库成功，但是RPC下发考试任务返回失败");
    }

    /**
     * 考试任务指派删除
     *
     * @author DragonDean
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        PaperAssign model = paperAssignMapper.selectOne(
                new QueryWrapper<PaperAssign>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        paperAssignMapper.updateById(model);
    }

}
